﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;
using System.Data.SqlClient;
using System.IO;
using System.Text;

public partial class SearchTest : System.Web.UI.Page
{

    //Create an Object of Manager classs
    Manager mgr = new Manager(true, "ConnectionString");
    protected localFunction obj = new localFunction();
    public string FeaturedDoctor_category_string = "";
    public enum FeaturedDoctorType { NonFeatured, Standard, Enhanced, Premium };

    public string tDoctorsId = "";
    public string frompage = "";
    public string TravelDis = "";
    public int gridcount = 0;
    int pageNoPre = 1;
    int pageNoEnh = 1;
    int pageNoStd = 1;
    int pageNoNon = 1;
    public string StdDoctorsId = "";

    public string UpdateQueryStringItem(System.Web.HttpRequest httpRequest, string queryStringKey, string newQueryStringValue)
    {
        StringBuilder NewURL = new StringBuilder();
        NewURL.Append(httpRequest.RawUrl);

        if (httpRequest.QueryString[queryStringKey] != null)
        {
            string OrignalSet = String.Format("{0}={1}", queryStringKey, httpRequest.QueryString[queryStringKey]);
            string NewSet = String.Format("{0}={1}", queryStringKey, newQueryStringValue);
            NewURL.Replace(OrignalSet, NewSet);
        }
        else if (httpRequest.QueryString.Count == 0)
        {
            NewURL.AppendFormat("?{0}={1}", queryStringKey, newQueryStringValue);
        }
        else
        {
            NewURL.AppendFormat("&{0}={1}", queryStringKey, newQueryStringValue);
        }
        return NewURL.ToString();
    }
    
    
    protected void Page_Load(object sender, EventArgs e)
    {

       
        Master.OASSpecialty = Session["Speciality"].ToString();

        bool bFeaDocsFound = false;
        bool bStdFeaDoc = false;
        bool bPreFeaDoc = false;
        bool bEnFeaDoc = false;
        

        try
        {
            pageNoPre = Convert.ToInt32(Request.QueryString["pageNoPre"]);
            if (pageNoPre == 0)
                pageNoPre = 1;
        }
        catch
        {
            pageNoPre = 1;
        }

        try
        {
            pageNoEnh = Convert.ToInt32(Request.QueryString["pageNoEnh"]);
            if (pageNoEnh == 0)
                pageNoEnh = 1;
        }
        catch
        {
            pageNoEnh = 1;
        }

        try
        {
            pageNoStd = Convert.ToInt32(Request.QueryString["pageNoStd"]);
            if (pageNoStd == 0)
                pageNoStd = 1;
        }
        catch
        {
            pageNoStd = 1;
        }

        try
        {
            pageNoNon = Convert.ToInt32(Request.QueryString["pageNoNon"]);
            if (pageNoNon == 0)
                pageNoNon = 1;
        }
        catch
        {
            pageNoNon = 1;
        }

        if (!Page.IsPostBack)
        {

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            ds = mgr.ExecuteQuery("get_featureSpecialty", "tbl");
            dt = ds.Tables[0];
            System.String vLink = string.Empty;

            if (dt.Rows.Count > 0)
            {
                FeaturedDoctor_category_string = "";
                for (int i = 8; i < dt.Rows.Count; i++)
                {
                    FeaturedDoctor_category_string += "<tr> <td><h3><a href=\"" + Session["strHttp"].ToString().Trim() + "Doctor/featured_doctors_speciality_" + getUrl(dt.Rows[i]["Name"]).ToString().Trim() + ".aspx" + "\">" + dt.Rows[i]["Name"].ToString() + "</a></h3></td> </tr>";
                }

               
            }
            TopDoctors();
            BindHospitals();
            bFeaDocsFound = (Session["sDoctorsId"] != null && Session["sDoctorsId"].ToString().Trim() != "");
            bStdFeaDoc = (Session["StdFeaDoctorsId"] != null && Session["StdFeaDoctorsId"].ToString().Trim() != "");
            bPreFeaDoc = (Session["PreDoctorsId"] != null && Session["PreDoctorsId"].ToString().Trim() != "");
            bEnFeaDoc = (Session["EnFeaDoctorsId"] != null && Session["EnFeaDoctorsId"].ToString().Trim() != "");


            if (Session["Travel_Dis"] != null && Session["Travel_Dis"].ToString().Trim() != "")
            { TravelDis = Session["Travel_Dis"].ToString(); }

            if (bFeaDocsFound || bStdFeaDoc || bPreFeaDoc || bEnFeaDoc)
            {
                //string to store all the doctor id's
                tDoctorsId = Session["sDoctorsId"].ToString();
                StdDoctorsId = Session["StdFeaDoctorsId"].ToString();

                // check the parent page
                try
                {
                    frompage = Session["pageFromOrAction"].ToString();
                }
                catch
                {
                    //frompage = "advanced";  
                }

                BindGrid(FeaturedDoctorType.NonFeatured);
                BindGrid(FeaturedDoctorType.Standard);
                BindGrid(FeaturedDoctorType.Enhanced);
                BindGrid(FeaturedDoctorType.Premium);
            }
            else
            {
                Response.Redirect("SearchDoctors_adv.aspx");
            }
        }
        else
        {
            BindGrid(FeaturedDoctorType.NonFeatured);
            BindGrid(FeaturedDoctorType.Standard);
            BindGrid(FeaturedDoctorType.Enhanced);
            BindGrid(FeaturedDoctorType.Premium);
        }

    }

    /// <summary>
    /// Bind one of the any four Grids as per the Featured Doctor Type
    /// </summary>
    /// <param name="FeatureType"></param>
    /// <author>Kajal Mandal</author>
    /// <date>17 Oct 2007</date>
    /// <editted>31 Oct 2007</editted>
    public void BindGrid(FeaturedDoctorType FeatureType)
    {
        string DoctorsId = string.Empty;
        DataSet ds;
        switch (FeatureType)
        {
            case FeaturedDoctorType.NonFeatured:
                #region Non Featured Doctors List
                DoctorsId = Convert.ToString(Session["sDoctorsId"]);
                if (DoctorsId.Length > 0)
                {

                    ds = mgr.ExecuteQuery(returnSql(GetPageId(pageNoNon, DoctorsId, "NonFeatured")), "tbl_drdet");

                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"] != null)  // to make distance column visibility true if search criteria includes Distance Search Functionality
                        {
                            ds.Tables[0].DefaultView.Sort = " distance,rating desc";
                            grdSearch.Columns[4].Visible = true;
                        }
                        else
                        {
                            ds.Tables[0].DefaultView.Sort = " rating desc";
                           // grdSearch.Columns[4].Visible = false;
                        }

                        grdSearch.DataSource = ds.Tables[0].DefaultView;
                        if (pageNoNon > grdSearch.PageCount)
                            grdSearch.PageIndex = 1;
                        else
                            grdSearch.PageIndex = pageNoNon;
                        grdSearch.DataBind();
                    }
                    //else
                    //{
                    //    tbl_feat.Visible = false;
                    //    lbl_FeaMsg.Text = "No more Featured Links";
                    //    lbl_FeaMsg.ForeColor = System.Drawing.Color.Red;
                    //}
                }
                else
                {
                    grdSearch.Visible = false;
                }
                #endregion
                break;
            case FeaturedDoctorType.Standard:
                #region Standard Featured Doctors List
                DoctorsId = Convert.ToString(Session["StdFeaDoctorsId"]);
                if (DoctorsId.Length > 0)
                {
                    ds = mgr.ExecuteQuery(returnSql(GetPageId(pageNoStd, DoctorsId, "Standard")), "tbl_drdet");
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"] != null)  // to make distance column visibility true if search criteria includes Distance Search Functionality
                        {
                            ds.Tables[0].DefaultView.Sort = " distance,rating desc";
                        }
                        else
                        {
                            ds.Tables[0].DefaultView.Sort = " rating desc";
                        }

                        StandardFeaDoc.DataSource = ds.Tables[0].DefaultView;
                        if (pageNoStd > StandardFeaDoc.PageCount)
                            StandardFeaDoc.PageIndex = 1;
                        else
                            StandardFeaDoc.PageIndex = pageNoStd;
                        StandardFeaDoc.DataBind();
                        //lbl_FeaMsg.Text = "Featured Links ";
                        //lbl_FeaMsg.ForeColor = System.Drawing.Color.Navy;
                        //lbl_FeaMsg.Font.Bold = true;
                        //lbl_FeaMsg.Font.Size = 11;
                        //tbl_feat.Visible = false; ;
                    }
                    else
                    {
                        //tbl_feat.Visible = false;
                        //lbl_FeaMsg.Text = "No more Featured Links";
                        //lbl_FeaMsg.ForeColor = System.Drawing.Color.Red;
                    }
                }
                else
                {
                    StandardFeaDoc.Visible = false;
                    //tbl_feat.Visible = false;

                }
                #endregion
                break;
            case FeaturedDoctorType.Enhanced:
                #region Enhanced Featured Doctors List
                DoctorsId = Convert.ToString(Session["EnFeaDoctorsId"]);
                if (DoctorsId.Length > 0)
                {
                    ds = mgr.ExecuteQuery(returnSql(GetPageId(pageNoEnh, DoctorsId, "Enhance")), "tbl_drdet");
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"] != null)  // to make distance column visibility true if search criteria includes Distance Search Functionality
                        {
                            ds.Tables[0].DefaultView.Sort = " distance,rating desc";
                            grdEnhanced.Columns[4].Visible = true;
                        }
                        else
                        {
                            ds.Tables[0].DefaultView.Sort = " rating desc";
                            grdEnhanced.Columns[4].Visible = false;
                        }

                        grdEnhanced.DataSource = ds.Tables[0].DefaultView;
                        if (pageNoEnh > grdEnhanced.PageCount)
                            grdEnhanced.PageIndex = 1;
                        else
                            grdEnhanced.PageIndex = pageNoEnh;
                        grdEnhanced.DataBind();
                        //lblMsgEnhance.Text = "Featured Links ";
                        //lblMsgEnhance.ForeColor = System.Drawing.Color.Navy;
                        //lblMsgEnhance.Font.Bold = true;
                        //lblMsgEnhance.Font.Size = 11;
                        //trEnhance.Visible = true;
                        //trEnhanceMsg.Visible = true;
                        //trEnhancePaging.Visible = true;
                    }
                    //else
                    //{
                    //    tbl_feat.Visible = false;
                    //    lbl_FeaMsg.Text = "No more Featured Links";
                    //    lbl_FeaMsg.ForeColor = System.Drawing.Color.Red;
                    //}
                }
                else
                {
                    grdEnhanced.Visible = false;
                }
                #endregion
                break;
            case FeaturedDoctorType.Premium:
                #region Premium Featured Doctors List
                DoctorsId = Convert.ToString(Session["PreDoctorsId"]);
                if (DoctorsId.Length > 0)
                {

                    ds = mgr.ExecuteQuery(returnSql(GetPageId(pageNoPre, DoctorsId, "Premium")), "tbl_drdet");
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"] != null)  // to make distance column visibility true if search criteria includes Distance Search Functionality
                        {
                            ds.Tables[0].DefaultView.Sort = " distance,rating desc";
                            grdPremium.Columns[4].Visible = true;
                        }
                        else
                        {
                            ds.Tables[0].DefaultView.Sort = " rating desc";
                           // grdPremium.Columns[4].Visible = false;
                        }

                        grdPremium.DataSource = ds.Tables[0].DefaultView;
                        if (pageNoPre > grdPremium.PageCount)
                            grdPremium.PageIndex = 1;
                        else
                            grdPremium.PageIndex = pageNoPre;
                        grdPremium.DataBind();
                       // lblMsgPremium.Text = "Featured Links ";
                       // lblMsgPremium.ForeColor = System.Drawing.Color.Navy;
                        //lblMsgPremium.Font.Bold = true;
                        //lblMsgPremium.Font.Size = 11;
                        //trPremium.Visible = true;
                        //trPremiumMsg.Visible = true;
                       // trPremiumPaging.Visible = true;
                    }
                    //else
                    //{
                    //    tbl_feat.Visible = false;
                    //    lbl_FeaMsg.Text = "No more Featured Links";
                    //    lbl_FeaMsg.ForeColor = System.Drawing.Color.Red;
                    //}
                }
                else
                {
                    grdPremium.Visible = false;
                }
                #endregion
                break;
        }
        return;
    }


    public string getPhoto(object photo, object sex)
    {
        string p = photo.ToString();
        if (p.Length > 0)
        {


            if (File.Exists(Request.PhysicalApplicationPath + "\\images\\Dr_images\\" + photo))
            {
                //string str_path = mgr.getThumbnaleImage(Session["strHttp"].ToString() + "images/Dr_images/" + photo, 80, 100, false, "");

                string str_path = getThumbnaleImageWithURLFormat(photo.ToString(), 130, 230, false, "", Session["strHTTP"].ToString());
                return str_path;
            }
            else
            {
                if (sex.ToString().ToLower() == "m")
                    return "<img height=\"230\" width=\"130\" src='" + Session["strHttp"].ToString() + "images/Dr_images/silhouette-male.gif'>";
                else
                    return "<img height=\"230\" width=\"130\" src='" + Session["strHttp"].ToString() + "images/Dr_images/silhouette--female.gif'>";
            }

        }
        else
        {
            if (sex.ToString().ToLower() == "m")
                return "<img height=\"230\" width=\"130\" src='" + Session["strHttp"].ToString() + "images/Dr_images/silhouette-male.gif'>";
            else
                return "<img height=\"230\" width=\"130\" src='" + Session["strHttp"].ToString() + "images/Dr_images/silhouette--female.gif'>";
        }
    }
    protected void btnBackToSearch_Click(object sender, EventArgs e)
    {
        string goToCode = "";
        //if (Request.QueryString["frompage"] != null && Request.QueryString["frompage"].ToString() == "")
        if (Session["pageFromOrAction"] != null && Session["pageFromOrAction"].ToString() != "")
        {
            //string tFrompage = Request.QueryString["frompage"].ToString().Trim();
            goToCode = Session["pageFromOrAction"].ToString();
            switch (goToCode)
            {
                case "home":
                case "simple":
                    Response.Redirect(Session["strHttps"] + "Default.aspx");
                    break;
                case "CommunityPage":
                    Response.Redirect(Session["strHttps"] + "Community/community.aspx");
                    break;
                case "doctorContent":
                    Response.Redirect(Session["strHttps"] + "Doctor/doctorContent.aspx");
                    break;
                case "RateDoctors":
                    Response.Redirect(Session["strHttp"] + "patient/patient_rate.aspx?fromPage=RateDoctors");
                    break;
                case "drMessage":
                    Response.Redirect(Session["strHttp"] + "boardsblogs/blogs.aspx");
                    break;
                case "advanced":
                    Response.Redirect(Session["strHttp"] + "SearchDoctors_adv.aspx");
                    break;
                default:
                    Response.Redirect(Session["strHttp"] + "SearchDoctors_adv.aspx");
                    break;
            }
        }
        else
            Response.Redirect(Session["strHttp"] + "SearchDoctors_adv.aspx");
    }


    string GetPageId(int pageNo, string id, string docType)
    {
        string did = id; // Session["sDoctorsId"].ToString();

        int StartIndex = getcPostion(pageNo, id);
        int lastIndex = getcPostion(pageNo + 1, id);
        int totalRecs = GetRecCount(did);

        string ids = did.Substring(StartIndex, lastIndex - StartIndex);
        ids = ids.TrimEnd(',').TrimStart(',');
        int startingRec = 10 * (pageNo - 1) + 1;
        int endingRec = startingRec + (GetRecCount(ids) - 1);

        switch (docType)
        {
            case "Premium":
               // litPaging.Text = "<table width='100%'><tr><td>Displaying " + startingRec + " to " + endingRec + " of " + totalRecs + "</td><td align='right'>";
                if (pageNo > 1)
                {
                    object page = pageNo - 1;
                   // litPaging.Text += "<a href='" + UpdateQueryStringItem(Page.Request, "pageNoPre", page.ToString()) + "'>Previous</a>";
                    //  litPaging.Text += "<a href='SearchResultsDocs.aspx?pageNoPre=" + (pageNo - 1) + "&" + Request.QueryString.ToString() + "'>Previous</a>";
                }
                if (pageNo < (totalRecs / 10) || (pageNo == (totalRecs / 10) && (totalRecs % 10) != 0))
                {
                    //litPaging.Text += "&nbsp;&nbsp;&nbsp;<a href='SearchResultsDocs.aspx?pageNoPre=" + (pageNo + 1) + "&" + Request.QueryString.ToString() + "'>Next</a>";
                    object page = pageNo + 1;
                   // litPaging.Text += "&nbsp;&nbsp;&nbsp;<a href='" + UpdateQueryStringItem(Page.Request, "pageNoPre", page.ToString()) + "'>Next</a>";
                }

              //  litPaging.Text += "</td></tr></table>";

                break;
            case "Enhance":
               // enhance.Text = "<table width='100%'><tr><td>Displaying " + startingRec + " to " + endingRec + " of " + totalRecs + "</td><td align='right'>";
                if (pageNo > 1)
                {
                    object page = pageNo - 1;
                   // enhance.Text += "<a href='" + UpdateQueryStringItem(Page.Request, "pageNoEnh", page.ToString()) + "'>Previous</a>";
                    // enhance.Text += "<a href='SearchResultsDocs.aspx?pageNoEnh=" + (pageNo - 1) + "&" + Request.QueryString.ToString() + "'>Previous</a>";
                }
                if (pageNo < (totalRecs / 10) || (pageNo == (totalRecs / 10) && (totalRecs % 10) != 0))
                {
                    object page = pageNo + 1;
                    //enhance.Text += "&nbsp;&nbsp;&nbsp;<a href='" + UpdateQueryStringItem(Page.Request, "pageNoEnh", page.ToString()) + "'>Next</a>";
                    // enhance.Text += "&nbsp;&nbsp;&nbsp;<a href='SearchResultsDocs.aspx?pageNoEnh=" + (pageNo + 1) + "&" + Request.QueryString.ToString() + "'>Next</a>";
                }
               // enhance.Text += "</td></tr></table>";
                //enhance.Text = "<table width='100%'><tr><td>Displaying " + startingRec + " to " + endingRec + " of " + totalRecs + "</td><td align='right'>";
                //if (pageNo > 1)
                //    enhance.Text += "<a href='SearchResultsDocs.aspx?pageNoEnh=" + (pageNo - 1) + "'>Previous</a>";
                //if (pageNo < (totalRecs / 10) || (pageNo == (totalRecs / 10) && (totalRecs % 10) != 0))
                //    enhance.Text += "&nbsp;&nbsp;&nbsp;<a href='SearchResultsDocs.aspx?pageNoEnh=" + (pageNo + 1) + "'>Next</a>";
                //litPaging.Text += "</td></tr></table>";
                break;
            case "Standard":
               // Standard.Text = "<table width='100%'><tr><td>Displaying " + startingRec + " to " + endingRec + " of " + totalRecs + "</td><td align='right'>";
                if (pageNo > 1)
                {
                    object page = pageNo - 1;
                    //Standard.Text += "<a href='" + UpdateQueryStringItem(Page.Request, "pageNoStd", page.ToString()) + "'>Previous</a>";
                    //  Standard.Text += "<a href='SearchResultsDocs.aspx?pageNoStd=" + (pageNo - 1) + "&" + Request.QueryString.ToString() + "'>Previous</a>";
                }
                if (pageNo < (totalRecs / 10) || (pageNo == (totalRecs / 10) && (totalRecs % 10) != 0))
                {
                    object page = pageNo + 1;
                    //Standard.Text += "&nbsp;&nbsp;&nbsp;<a href='" + UpdateQueryStringItem(Page.Request, "pageNoStd", page.ToString()) + "'>Next</a>";
                    //   Standard.Text += "&nbsp;&nbsp;&nbsp;<a href='SearchResultsDocs.aspx?pageNoStd=" + (pageNo + 1) + "&" + Request.QueryString.ToString() + "'>Next</a>";
                }
               // Standard.Text += "</td></tr></table>";
                break;
            case "NonFeatured":
                Normal.Text = "<table width='100%'><tr><td>Displaying " + startingRec + " to " + endingRec + " of " + totalRecs + "</td><td align='right'>";
                if (pageNo > 1)
                {
                    object page = pageNo - 1;
                    Normal.Text += "<a href='" + UpdateQueryStringItem(Page.Request, "pageNoNon", page.ToString()) + "'>Previous</a>";
                    //   Normal.Text += "<a href='SearchResultsDocs.aspx?pageNoNon=" + (pageNo - 1) + "&" + Request.QueryString.ToString() + "'>Previous</a>";
                }
                if (pageNo < (totalRecs / 10) || (pageNo == (totalRecs / 10) && (totalRecs % 10) != 0))
                {
                    object page = pageNo + 1;
                    Normal.Text += "&nbsp;&nbsp;&nbsp;<a href='" + UpdateQueryStringItem(Page.Request, "pageNoNon", page.ToString()) + "'>Next</a>";
                    //   Normal.Text += "&nbsp;&nbsp;&nbsp;<a href='SearchResultsDocs.aspx?pageNoNon=" + (pageNo + 1) + "&" + Request.QueryString.ToString() + "'>Next</a>";
                }
                Normal.Text += "</td></tr></table>";
                break;
        }

        //     litPagingBelow.Text = litPaging.Text;
        return ids;
    }

    int getcPostion(int pageNo, string id)
    {
        string did = id; // Session["sDoctorsId"].ToString();
        int startNo = (pageNo - 1) * 10;
        int pos = 0;
        int pr = 0;
        //   Response.Write("startNo: " + startNo + "<BR>");
        for (int i = 0; i < startNo; i++)
        {
            pos = did.IndexOf(',', pr);
            //     Response.Write("<BR>Pos: " + pos);
            pr = pos + 1;
            if (did.IndexOf(',', pr) == -1)
            {
                pos = did.Length;
                break;
            }
        }
        return pos;
    }

    private int GetRecCount(string csvStr)
    {
        return csvStr.Split(new char[] { ',' }).Length;
    }

    #region Query
    /// <summary>
    /// Inline query has been wirtten because long id string cannot be pass to stored procedure
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    string returnSql(string ids)
    {
        //        //Response.Write(ids); 
        //        Manager mgr = new Manager(true,"ConnectionString");
        string strSql = @"select qu from func_rating()";
        SqlDataReader dr = mgr.ExecuteQuery(strSql);
        System.String orderClause = "";
        System.String AttachMiles = "";
        //        System.String OrderBy = "id";

        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"] != null) //  to order the result first by Distance and then by rating Desc / to Calculate Miles
        {
            orderClause = "order by Distance ASC, Rating Desc";
            AttachMiles = " , (dbo.GetDistanceInMiles('" + Session["ZipCode"].ToString() + "','" + Session["City"].ToString() + "','" + Session["State"].ToString() + "',zipcodeforsearch)) as Distance";
        }
        else
        {
            orderClause = "order by Rating Desc";
            AttachMiles = ",'' as distance";
        }
        if (dr.Read())
        {
            strSql = @"select d.city, d.zipcode,  
                        case when (select tbl_primaryspeciality.name from tbl_primaryspeciality where 
    						tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid) is null
	                    then 
		                    (select tbl_secondaryspeciality.name from tbl_secondaryspeciality where
						    tbl_secondaryspeciality.id=d.secondaryspecialityid)
	                    else
		                    (select tbl_primaryspeciality.name from tbl_primaryspeciality where 
						    tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid)
	                    end 
                        as SubSpec,
                        rtrim((select name from tbl_states where stateId = d.state)) as state,
                        Sp.name as specialityName,
                        CAST((" + dr[0].ToString() + @") as numeric(8,2)) as Rating,d.id as id,fname+' '+isnull(mname,'')+' '+lname as docname,address1+'<br>'+city+', '+state as address,
                         Sp.name+isnull(', '+(select tbl_primaryspeciality.name from tbl_primaryspeciality where 
						tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid)
						 ,'')+
						isnull(', ' + (select tbl_secondaryspeciality.name from tbl_secondaryspeciality where
						tbl_secondaryspeciality.name not in(Sp.name,p.name) and
						 tbl_secondaryspeciality.id=d.secondaryspecialityid )
                        ,'')
                        as speciality,
                       isnull(dp.website,'')as website,isnull(dp.photo,'') as photo,d.gender,d.Phone,d.Fax " + AttachMiles + @" 
                        from tbl_doctors d
                        left outer join tbl_doctor_hospital h on h.dr_id=d.id

                        left outer join tbl_primaryspeciality p on p.id=d.primaryspecialityid 
                        left outer join tbl_secondaryspeciality s on s.id=d.secondaryspecialityid 
                        left outer join tbl_DrPremium dp on dp.dr_id=d.id
                        left outer join tbl_speciality sp on sp.id=D.specialityid                        
                        where  d.isdelete=0 and d.id in (" + ids + ")" + orderClause; //Km/Ad        
        }
        dr.Close();
        return strSql;
        //        if (dr.Read())
        //        {
        //            strSql = @"select d.city, d.zipcode,  
        //                        case when (select tbl_primaryspeciality.name from tbl_primaryspeciality where 
        //    						tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid) is null
        //	                    then 
        //		                    (select tbl_secondaryspeciality.name from tbl_secondaryspeciality where
        //						    tbl_secondaryspeciality.id=d.secondaryspecialityid)
        //	                    else
        //		                    (select tbl_primaryspeciality.name from tbl_primaryspeciality where 
        //						    tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid)
        //	                    end 
        //                        as SubSpec,
        //                        rtrim((select name from tbl_states where stateId = d.state)) as state,
        //                        Sp.name as specialityName,
        //                        CAST((" + dr[0].ToString() + @") as numeric(8,2)) as Rating,d.id as id,fname+' '+mname+' '+lname as docname,address1+'<br>'+city+', '+state as address,
        //                         Sp.name+isnull(', '+(select tbl_primaryspeciality.name from tbl_primaryspeciality where 
        //						tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid)
        //						 ,'')+
        //						isnull(', ' + (select tbl_secondaryspeciality.name from tbl_secondaryspeciality where
        //						tbl_secondaryspeciality.name not in(Sp.name,p.name) and
        //						 tbl_secondaryspeciality.id=d.secondaryspecialityid )
        //                        ,'')
        //                        as speciality,
        //                        isnull(dp.website,'')as website,isnull(dp.photo,'') as photo,d.gender " + AttachMiles + @" 
        //                        from tbl_doctors d
        //                        left outer join tbl_primaryspeciality p on p.id=d.primaryspecialityid 
        //                        left outer join tbl_secondaryspeciality s on s.id=d.secondaryspecialityid 
        //                        left outer join tbl_DrPremium dp on dp.dr_id=d.id
        //                        left outer join tbl_speciality sp on sp.id=D.specialityid                        
        //                        where  d.isdelete=0 and d.id in (" + ids + ")" + orderClause; //Km/Ad        
        //        }
        //        dr.Close();
        //        return strSql;

        //        if ((state.Length > 0 && zip.Length > 0) || (city.Length > 0 && zip.Length > 0))
        //        {
        //strSql = @"Select * from (Select 'SrNo' = ROW_NUMBER() OVER(ORDER BY " + OrderBy + " ),t1.* from (" +
        //             "select CAST((" + strSql + ") as numeric(8,2)) as Rating, d.id, fname+' '+mname+' '+lname as DocName," +
        //             "address1+'<br>'+city+','+state as address, "+     
        //             "Sp.[name]+isnull(', '+(select tbl_primaryspeciality.name " +
        //             "from tbl_primaryspeciality where tbl_primaryspeciality.name not in(Sp.name)" +       
        //             "and tbl_primaryspeciality.id=d.primaryspecialityid),'') + " +      
        //             "isnull(', ' + (select tbl_secondaryspeciality.name " +       
        //             "from tbl_secondaryspeciality where tbl_secondaryspeciality.name not in(Sp.name,p.name) " +
        //             "and tbl_secondaryspeciality.id=d.secondaryspecialityid),'') as speciality, isnull(dp.website,'') as website," +
        //             "isnull(dp.photo,'') as photo, d.gender " + AttachMiles +      
        //             " from tbl_doctors d left outer join tbl_primaryspeciality p on p.id=d.primaryspecialityid " + 
        //             "left outer join tbl_secondaryspeciality s on s.id=d.secondaryspecialityid "  +
        //             "left outer join tbl_DrPremium dp on dp.dr_id=d.id " + 
        //             "left outer join tbl_speciality sp on sp.id=D.specialityid " +
        //             "where  d.isdelete=0 and d.id in ('" + ids + "')" +
        //             ")as t1) as s where SrNo BETWEEN '" +
        //             "CAST(((" + pageNo + "- 1) * " + pageNo + " + 1) AS VARCHAR(15)) +' AND ' " +
        //             "CAST((" + pageNo + "* " + pageNo + ")AS VARCHAR(15)) + ' ORDER BY Distance, Rating desc";
        //}
        //    return strSql;
    }


    public string getThumbnaleImageWithURLFormat(string imgName, int maxWidth, int maxHeight, bool saveImage, string savePath, string baseURL)
    {
        string s;
        double imgHeight, imgWidth;
        //Response.Write(imgName) ;
        s = Server.MapPath("~/images/dr_images/" + imgName);
        //Response.Write("</br>"+s);
        System.Drawing.Image currentImage = System.Drawing.Image.FromFile(s);
        imgHeight = currentImage.Height;
        imgWidth = currentImage.Width;
        if (imgWidth > maxWidth | imgHeight > maxHeight)
        {
            double deltaWidth = imgWidth - maxWidth;
            double deltaHeight = imgHeight - maxHeight;
            double scaleFactor;
            if (deltaHeight > deltaWidth)
                scaleFactor = maxHeight / imgHeight;
            else
                scaleFactor = maxWidth / imgWidth;
            imgWidth *= scaleFactor;
            imgHeight *= scaleFactor;
        }

        if (saveImage)
        {
            if (savePath == "")
                throw new Exception("must pass a file name");
            currentImage.GetThumbnailImage(Convert.ToInt32(imgWidth), Convert.ToInt32(imgHeight), null, IntPtr.Zero).Save(Server.MapPath(savePath));
            currentImage.Dispose();
        }
        //return currentImage.GetThumbnailImage(Convert.ToInt32(imgWidth), Convert.ToInt32(imgHeight), null, IntPtr.Zero);


        return ("<img src=\"" + baseURL + "images/dr_images/" + imgName + "\"" + " height=\"" + imgHeight + "\" width=\"" + imgWidth + "\" border='0' alt=''/>");
    }

    public void TopDoctors()
    {
        SqlParameter[] sqlparam = new SqlParameter[0];
        DataSet ds = CustomRepository.CustumDataSetFunction("get_top_10_Docotors", sqlparam);
        TopDocRepeater.DataSource = ds;
        TopDocRepeater.DataBind();
       
        
    }
    protected string getUrl(object st)
    {
        return st.ToString().Replace(" & ", " and ").Replace(" ", "_").ToLower().Replace(",", "-or-");
    }
    public void BindHospitals()
    {

        var sqlparam = new SqlParameter[0];
        var ds = CustomRepository.CustumDataSetFunction("Get_InterNational_Hospitals", sqlparam);


        //Latest_Hospital_Repeater.DataSource = ds.Tables[0];
        //Latest_Hospital_Repeater.DataBind();

        //Featured_Hospital_Repeater.DataSource = ds.Tables[1];
        //Featured_Hospital_Repeater.DataBind();

        Top_Hospital_Repeater.DataSource = ds.Tables[2];
        Top_Hospital_Repeater.DataBind();
        Session["Top_Hospitals"] = ds.Tables[2];

        
    }

    public void GetGoogleImage(string address)
    {
       // lnkGoogle.NavigateUrl = "http://maps.google.com/maps?q=" + Server.UrlEncode(address) + "&num=1&start=0";
        //lnkGoogle1.NavigateUrl = "http://maps.google.com/maps?q=" + Server.UrlEncode(address) + "&t=h&num=1&start=0&hl=en";
    }
    #endregion



}
